<?php
/**
 * This file is part of DomAr.
 * 
 * DomAr is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * DomAr is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with DomAr.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @link http://inditel.ee/
 * @copyright 2007-2009 Inditel Meedia OÜ
 * @author Oliver Leisalu <oliver@inditel.ee>
 */

/**
* @package DomAr
* @subpackage DomArChangeLog
*/
class DomArClassRecordProperty_ChangeLog extends DomArProperty_Plugin implements IDomArPropertyInsertListener,IDomArPropertyUpdateListener  {
	
	
	protected $childClassName;
	
	
	public function __construct( $name, $childClassName ) {
		parent::__construct( $name );
		$this->childClassName = $childClassName;
	}
	
	public function init( DomArObject $object, array &$values ) {
		return NULL;
	}
	
	public function validate( DomArObject $object, &$propertyValue, array &$customParams = array()) {
		return spl_object_hash($propertyValue) == spl_object_hash($object->{$this->name}) ? 0 : 1;
	}
	
	public function load( DomArObject $object, &$propertyValue ) {
		return new DomArChangeLog( $object, $this );
	}
	
	public function isLoaded( DomArObject $object, &$propertyValue ) {
		return is_object($propertyValue);
	}
	
	public function alterTable( DomArTable $table ) {
		call_user_func( array($this->childClassName,'getTable') )->update();
		return;
	}
	
	public function insert( DomArObject $object, &$propertyValue, DomArValueSet $set ) {
		$object->setChanged($this->name,true);
	}
	
	public function update( DomArObject $object, &$propertyValue, DomArValueSet $set ) {
		foreach( $object->{$this->name}->getNewChanges() as $change ) {
			if( $change->objectId == NULL ) {
				$change->objectId = $object->id;
				$change->value = $change->parseValue( $object, $object->{$change->propertyName} );
			}
			$change->save();
		}
		$object->{$this->name}->removeAllNewChanges();
	}
	
	public function registerChange( DomArObject $object, &$propertyValue, $propertyName ) {
		
		$cl = $this->childClassName;
		$c = new $cl;
		$c->ip = ip();
		$c->datetime = 'now';
		//$c->objectId = $object->id;
		$c->objectClassName = get_class($object);
		$c->propertyName = $propertyName;
		//$c->value = $c->parseValue( $object, $propertyValue );
		$c->prepare( $object );
		
		$object->{$this->name}->addChange($c);
		$object->setChanged( $this->name, true );
	}
	

}
?>